/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.easemob.chatuidemo.activity;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.exceptions.EaseMobException;
import com.nostra13.universalimageloader.core.ImageLoader;

import net.mihome.app.AppContext;
import net.mihome.app.AppException;
import net.mihome.app.R;
import net.mihome.app.bean.Tweet;
import net.mihome.app.bean.User;
import net.mihome.app.common.FileUtils;
import net.mihome.app.common.ImageUtils;
import net.mihome.app.common.StringUtils;
import net.mihome.app.common.UIHelper;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class NewGroupActivity extends BaseActivity {
	private EditText groupNameEditText;
	private ProgressDialog progressDialog;
	private EditText introductionEditText;
	private CheckBox checkBox;
	private CheckBox memberCheckbox;
	private CheckBox freeJoinCheckbox;
	private LinearLayout openInviteContainer;
	private LinearLayout freeJoinContainer;
    private ImageView avatar;
    private InputMethodManager imm;
    private final static int GROUP_AVATAR_CHOICE_SDCARD=101;  //从sd卡中取图片
    private final static int GROUP_AVATAR_CHOICE_CANMA=102;   //照相机
    private final static int GROUP_MEMBER_CHOICE=103;   //照相机
    private String theLarge;
    private String theThumbnail;
    public Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_new_group);
		groupNameEditText = (EditText) findViewById(R.id.edit_group_name);
		introductionEditText = (EditText) findViewById(R.id.edit_group_introduction);
		checkBox = (CheckBox) findViewById(R.id.cb_public);
        freeJoinCheckbox = (CheckBox) findViewById(R.id.cb_join_free);
		memberCheckbox = (CheckBox) findViewById(R.id.cb_member_inviter);
        freeJoinContainer = (LinearLayout) findViewById(R.id.ll_join_free);
		openInviteContainer = (LinearLayout) findViewById(R.id.ll_open_invite);
        avatar= (ImageView) findViewById(R.id.avatar);
        // 软键盘管理类
        imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
					openInviteContainer.setVisibility(View.GONE);
                    freeJoinContainer.setVisibility(View.VISIBLE);
				}else{
					openInviteContainer.setVisibility(View.VISIBLE);
                    freeJoinContainer.setVisibility(View.GONE);
				}
			}
		});
        avatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 隐藏软键盘
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                // 隐藏表情
                CharSequence[] items = {
                        NewGroupActivity.this.getString(R.string.img_from_album),
                        NewGroupActivity.this.getString(R.string.img_from_camera)};
                imageChooseItem(items);
            }
        });
        handler=new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {

                if(progressDialog!=null&&progressDialog.isShowing()){
                    progressDialog.dismiss();
                }
                switch (message.what){
                    case 1:{
                        Toast.makeText(NewGroupActivity.this,"图片上传成功",Toast.LENGTH_SHORT).show();
                        break;
                    }
                    case -1:{
                        Toast.makeText(NewGroupActivity.this,"图片上传失败，请到群设置中设置",Toast.LENGTH_SHORT).show();
                        break;
                    }
                }

                return false;
            }
        });
	}

	/**
	 * @param v
	 */
	public void save(View v) {
		String name = groupNameEditText.getText().toString();
		if (TextUtils.isEmpty(name)) {
			Intent intent = new Intent(this, AlertDialog.class);
			intent.putExtra("msg", "群组名称不能为空");
			startActivity(intent);
		} else {
			// 进通讯录选人
			startActivityForResult(new Intent(this, GroupPickContactsActivity.class).putExtra("groupName", name), GROUP_MEMBER_CHOICE);
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        String selectedImagePath=null;
        Bitmap bitmap = null;
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {

            if(requestCode==GROUP_MEMBER_CHOICE){
                //新建群组
                progressDialog = new ProgressDialog(this);
                progressDialog.setMessage("正在创建圈子...");
                progressDialog.setCanceledOnTouchOutside(false);
                progressDialog.show();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // 调用sdk创建群组方法
                        String groupName = groupNameEditText.getText().toString().trim();
                        String desc = introductionEditText.getText().toString();
                        String[] members = data.getStringArrayExtra("newmembers");
                        final EMGroup emGroup;
                        try {
                            if(checkBox.isChecked()){
                                //创建公开群，此种方式创建的群，可以自由加入
//							    emGroup=EMGroupManager.getInstance().createPublicGroup(groupName, desc, members, false);
                                //创建公开群，此种方式创建的群，用户需要申请，等群主同意后才能加入此群
                                emGroup=EMGroupManager.getInstance().createPublicGroup(groupName, desc, members, !freeJoinCheckbox.isChecked());
                                pubTweet(groupName,desc);
                            }else{
                                //创建不公开群
                                emGroup=EMGroupManager.getInstance().createPrivateGroup(groupName, desc, members, memberCheckbox.isChecked());
                            }
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    uploadAvatar(emGroup.getGroupId());
                                    progressDialog.dismiss();
                                    setResult(RESULT_OK);
                                    finish();
                                }
                            });
                        } catch (final EaseMobException e) {
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    progressDialog.dismiss();
                                    Toast.makeText(NewGroupActivity.this, "创建群组失败:" + e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
                                }
                            });
                        }

                    }
                }).start();
            }else if(requestCode==GROUP_AVATAR_CHOICE_CANMA){
                //如果是从照相机照相
                if (bitmap == null && !StringUtils.isEmpty(theLarge)) {
                    bitmap = ImageUtils.loadImgThumbnail(theLarge, 100, 100);
                }
                avatar.setImageBitmap(bitmap);
                avatar.setTag(theLarge);
            }else if(requestCode==GROUP_AVATAR_CHOICE_SDCARD){
                //如果是从sd卡选择
                Uri selectedImageUri = data.getData();
                if (selectedImageUri != null) {
                    selectedImagePath = ImageUtils.getImagePath( selectedImageUri, NewGroupActivity.this);
                }

                if (selectedImagePath != null) {
                    theLarge = selectedImagePath;
                } else {
                    bitmap = ImageUtils.loadPicasaImageFromGalley(selectedImageUri, NewGroupActivity.this);
                }
                if (AppContext.isMethodsCompat(android.os.Build.VERSION_CODES.ECLAIR_MR1)) {
                    String imaName = FileUtils.getFileName(theLarge);
                    if (imaName != null)
                        bitmap = ImageUtils.loadImgThumbnail(NewGroupActivity.this,
                                imaName,
                                MediaStore.Images.Thumbnails.MICRO_KIND);
                }
                if (bitmap == null && !StringUtils.isEmpty(theLarge))
                    bitmap = ImageUtils.loadImgThumbnail(theLarge, 100, 100);
                avatar.setImageBitmap(bitmap);
                avatar.setTag(theLarge);
            }
		}
	}

	public void back(View view) {
		finish();
	}
    /**
     * 创建群成功之后，发送一个大字报
     * */
    public void pubTweet(String groupName,String desc){
        User user=AppContext.getInstance().getLoginInfo();
        if(user==null){
            return ;
        }
        final Tweet tweet = new Tweet();
        tweet.setAuthorId(user.getUid());
        tweet.setBody("我创建了一个邻里圈:"+groupName+"<br>宗旨是："+desc+"<br>----大家都来捧捧场吧~");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    AppContext.getInstance().pubTweet(tweet);
                } catch (AppException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    /**
     * 操作选择
     *
     * @param items
     */
    public void imageChooseItem(CharSequence[] items) {
        android.app.AlertDialog imageDialog = new android.app.AlertDialog.Builder(this)
                .setTitle(R.string.ui_insert_image)
                .setIcon(android.R.drawable.btn_star)
                .setItems(items, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        // 手机选图
                        if (item == 0) {
                            Intent intent;
                            if (Build.VERSION.SDK_INT < 19) {
                                intent = new Intent();
                                intent.setAction(Intent.ACTION_GET_CONTENT);
                                intent.setType("image/*");
                                startActivityForResult(
                                        Intent.createChooser(intent, "选择图片"),
                                        GROUP_AVATAR_CHOICE_SDCARD);
                            } else {
                                intent = new Intent(
                                        Intent.ACTION_PICK,
                                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                intent.setType("image/*");
                                startActivityForResult(
                                        Intent.createChooser(intent, "选择图片"),
                                        GROUP_AVATAR_CHOICE_SDCARD);
                            }
                        }
                        // 拍照
                        else if (item == 1) {
                            String savePath = "";
                            // 判断是否挂载了SD卡
                            String storageState = Environment
                                    .getExternalStorageState();
                            if (storageState.equals(Environment.MEDIA_MOUNTED)) {
                                savePath = Environment
                                        .getExternalStorageDirectory()
                                        .getAbsolutePath()
                                        + "/OSChina/Camera/";// 存放照片的文件夹
                                File savedir = new File(savePath);
                                if (!savedir.exists()) {
                                    savedir.mkdirs();
                                }
                            }

                            // 没有挂载SD卡，无法保存文件
                            if (StringUtils.isEmpty(savePath)) {
                                UIHelper.ToastMessage(NewGroupActivity.this,
                                        "无法保存照片，请检查SD卡是否挂载");
                                return;
                            }

                            String timeStamp = new SimpleDateFormat(
                                    "yyyyMMddHHmmss").format(new Date());
                            String fileName = "mihome_" + timeStamp + ".jpg";// 照片命名
                            File out = new File(savePath, fileName);
                            Uri uri = Uri.fromFile(out);

                            theLarge = savePath + fileName;// 该照片的绝对路径

                            Intent intent = new Intent(
                                    MediaStore.ACTION_IMAGE_CAPTURE);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                            startActivityForResult(intent,
                                    GROUP_AVATAR_CHOICE_CANMA);
                        }
                    }
                }).create();

        imageDialog.show();
    }
    /**
     *
     * 上传群头像图片
     * */
    public void uploadAvatar(final String groupId){
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 存放照片的文件夹
                String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/mihome/Camera/";
                String largeFileName = FileUtils.getFileName(theLarge);
                String largeFilePath = savePath + largeFileName;

                // 生成上传的800宽度图片
                String thumbFileName = "thumb_" + largeFileName;
                theThumbnail = savePath + thumbFileName;
                Message msg = new Message();
                try {
                    // 压缩上传的图片
                    File tFile=new File(theThumbnail);
                    if(tFile.exists()){
                        tFile.delete();
                        ImageLoader.getInstance().clearMemoryCache();
                    }
                    ImageUtils.createImageThumbnail(NewGroupActivity.this,theLarge, theThumbnail, 800, 80);
                    File imgFile = new File(theThumbnail);
                    String imageUrl=AppContext.getInstance().uploadImage(imgFile,groupId);
                    //imageFile可以作为上传
                    msg.what = 1;
                    msg.obj = imageUrl;
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                    msg.what = -1;
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }
}
